import React, { useState } from 'react';
import {
  View,
  Text,
  StyleSheet,
  ScrollView,
  TouchableOpacity,
  Dimensions,
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import { BarChart } from 'react-native-chart-kit';
import Icon from 'react-native-vector-icons/MaterialIcons';

const { width } = Dimensions.get('window');

const PortfolioScreen = ({ navigation }) => {
  const [selectedTimeframe, setSelectedTimeframe] = useState('7D');
  const [portfolioData, setPortfolioData] = useState({
    totalValue: 12543.87,
    totalProfit: 234.56,
    profitPercentage: 1.89,
    assets: [
      { symbol: 'BTC', name: 'Bitcoin', amount: 0.5234, value: 12450.32, profit: 123.45 },
      { symbol: 'ETH', name: 'Ethereum', amount: 2.3456, value: 4567.89, profit: -45.67 },
      { symbol: 'USDT', name: 'Tether', amount: 1000, value: 1000, profit: 0.01 },
    ],
  });

  const timeframes = ['1D', '7D', '1M', '3M', '1Y', 'ALL'];

  const chartData = {
    labels: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
    datasets: [
      {
        data: [12000, 12300, 12100, 12500, 12400, 12600, 12543],
      },
    ],
  };

  const chartConfig = {
    backgroundColor: '#1a1a2e',
    backgroundGradientFrom: '#1a1a2e',
    backgroundGradientTo: '#16213e',
    decimalPlaces: 0,
    color: (opacity = 1) => `rgba(76, 175, 80, ${opacity})`,
    labelColor: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
    style: {
      borderRadius: 16,
    },
    propsForBackgroundLines: {
      stroke: '#333',
    },
  };

  return (
    <LinearGradient colors={['#1a1a2e', '#16213e']} style={styles.container}>
      <ScrollView
        contentContainerStyle={styles.scrollContent}
        showsVerticalScrollIndicator={false}
      >
        {/* Header */}
        <View style={styles.header}>
          <Text style={styles.title}>投资组合</Text>
          <TouchableOpacity onPress={() => navigation.navigate('Settings')}>
            <Icon name="settings" size={24} color="#fff" />
          </TouchableOpacity>
        </View>

        {/* Portfolio Summary */}
        <View style={styles.summaryCard}>
          <Text style={styles.summaryLabel}>总资产价值</Text>
          <Text style={styles.summaryValue}>${portfolioData.totalValue.toLocaleString()}</Text>
          <View style={styles.profitContainer}>
            <Text style={[
              styles.profitText,
              portfolioData.totalProfit >= 0 ? styles.positive : styles.negative
            ]}>
              ${Math.abs(portfolioData.totalProfit).toLocaleString()}
            </Text>
            <Text style={[
              styles.profitPercentage,
              portfolioData.totalProfit >= 0 ? styles.positive : styles.negative
            ]}>
              ({portfolioData.profitPercentage >= 0 ? '+' : ''}{portfolioData.profitPercentage}%)
            </Text>
          </View>
        </View>

        {/* Timeframe Selector */}
        <ScrollView
          horizontal
          showsHorizontalScrollIndicator={false}
          style={styles.timeframeContainer}
        >
          {timeframes.map((timeframe) => (
            <TouchableOpacity
              key={timeframe}
              style={[
                styles.timeframeButton,
                selectedTimeframe === timeframe && styles.selectedTimeframe,
              ]}
              onPress={() => setSelectedTimeframe(timeframe)}
            >
              <Text style={[
                styles.timeframeText,
                selectedTimeframe === timeframe && styles.selectedTimeframeText,
              ]}>
                {timeframe}
              </Text>
            </TouchableOpacity>
          ))}
        </ScrollView>

        {/* Performance Chart */}
        <View style={styles.chartContainer}>
          <Text style={styles.sectionTitle}>表现图表</Text>
          <BarChart
            data={chartData}
            width={width - 40}
            height={200}
            chartConfig={chartConfig}
            style={styles.chart}
          />
        </View>

        {/* Asset List */}
        <View style={styles.assetsContainer}>
          <Text style={styles.sectionTitle}>资产详情</Text>
          {portfolioData.assets.map((asset, index) => (
            <TouchableOpacity
              key={index}
              style={styles.assetItem}
              onPress={() => navigation.navigate('QRDeposit')}
            >
              <View style={styles.assetLeft}>
                <View style={styles.assetIcon}>
                  <Text style={styles.assetSymbol}>{asset.symbol}</Text>
                </View>
                <View>
                  <Text style={styles.assetName}>{asset.name}</Text>
                  <Text style={styles.assetAmount}>{asset.amount} {asset.symbol}</Text>
                </View>
              </View>
              <View style={styles.assetRight}>
                <Text style={styles.assetValue}>${asset.value.toLocaleString()}</Text>
                <Text style={[
                  styles.assetProfit,
                  asset.profit >= 0 ? styles.positive : styles.negative
                ]}>
                  {asset.profit >= 0 ? '+' : ''}${Math.abs(asset.profit).toLocaleString()}
                </Text>
              </View>
            </TouchableOpacity>
          ))}
        </View>

        {/* Action Buttons */}
        <View style={styles.actionContainer}>
          <TouchableOpacity
            style={[styles.actionButton, styles.depositButton]}
            onPress={() => navigation.navigate('QRDeposit')}
          >
            <Icon name="add" size={20} color="#fff" />
            <Text style={styles.actionButtonText}>存入</Text>
          </TouchableOpacity>
          <TouchableOpacity style={[styles.actionButton, styles.withdrawButton]}>
            <Icon name="remove" size={20} color="#fff" />
            <Text style={styles.actionButtonText}>提取</Text>
          </TouchableOpacity>
        </View>
      </ScrollView>
    </LinearGradient>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  scrollContent: {
    padding: 20,
  },
  header: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20,
  },
  title: {
    fontSize: 24,
    fontWeight: 'bold',
    color: '#fff',
  },
  summaryCard: {
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    borderRadius: 20,
    padding: 25,
    marginBottom: 20,
    alignItems: 'center',
  },
  summaryLabel: {
    fontSize: 16,
    color: '#a0a0a0',
    marginBottom: 5,
  },
  summaryValue: {
    fontSize: 32,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 10,
  },
  profitContainer: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  profitText: {
    fontSize: 18,
    fontWeight: 'bold',
    marginRight: 5,
  },
  profitPercentage: {
    fontSize: 14,
  },
  positive: {
    color: '#4CAF50',
  },
  negative: {
    color: '#f44336',
  },
  timeframeContainer: {
    flexDirection: 'row',
    marginBottom: 20,
  },
  timeframeButton: {
    paddingHorizontal: 20,
    paddingVertical: 10,
    marginRight: 10,
    borderRadius: 20,
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
  },
  selectedTimeframe: {
    backgroundColor: '#4CAF50',
  },
  timeframeText: {
    color: '#a0a0a0',
    fontSize: 14,
  },
  selectedTimeframeText: {
    color: '#fff',
  },
  chartContainer: {
    marginBottom: 30,
  },
  sectionTitle: {
    fontSize: 18,
    fontWeight: 'bold',
    color: '#fff',
    marginBottom: 15,
  },
  chart: {
    borderRadius: 16,
  },
  assetsContainer: {
    marginBottom: 20,
  },
  assetItem: {
    backgroundColor: 'rgba(255, 255, 255, 0.1)',
    borderRadius: 15,
    padding: 15,
    marginBottom: 10,
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
  },
  assetLeft: {
    flexDirection: 'row',
    alignItems: 'center',
  },
  assetIcon: {
    width: 40,
    height: 40,
    borderRadius: 20,
    backgroundColor: '#4CAF50',
    justifyContent: 'center',
    alignItems: 'center',
    marginRight: 15,
  },
  assetSymbol: {
    color: '#fff',
    fontWeight: 'bold',
  },
  assetName: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#fff',
  },
  assetAmount: {
    fontSize: 14,
    color: '#a0a0a0',
  },
  assetRight: {
    alignItems: 'flex-end',
  },
  assetValue: {
    fontSize: 16,
    fontWeight: 'bold',
    color: '#fff',
  },
  assetProfit: {
    fontSize: 14,
    fontWeight: 'bold',
  },
  actionContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
  },
  actionButton: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'center',
    borderRadius: 15,
    paddingVertical: 15,
    marginHorizontal: 5,
  },
  depositButton: {
    backgroundColor: '#4CAF50',
  },
  withdrawButton: {
    backgroundColor: '#f44336',
  },
  actionButtonText: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
    marginLeft: 5,
  },
});

export default PortfolioScreen;
